import { _decorator, Node, Prefab, instantiate, ScrollView, UITransform } from 'cc';
import { App } from '../../App';
import UtilTool from '../../tools/UtilTool';
import { PD } from '../../player/PlayerData';
import { HeadItem } from './HeadItem';
import { Component } from 'cc';
import wsTool from '../../net/ws';
import CommConst from '../../const/CommConst';
import { showErrorTip, showTip } from '../../tools/PopuUp';
import { EventConst } from '../../common/Common';
const { ccclass, property } = _decorator;

// 更换头像界面
@ccclass('ChangeHead')
export class ChangeHead extends Component {
    @property(Node)
    bg: Node = null

    @property(Prefab)
    headPrefab: Prefab = null

    @property(ScrollView)
    scroll: ScrollView = null

    headCount = 4   // 头像个数
    curItem: HeadItem = null

    onLoad() {
        UtilTool.setScreen(this.node)
        UtilTool.nodeActive(this.bg, 5)

    }

    start() {
        this.setData()
    }

    // 设置头像数据
    setData() {
        let allH = Math.ceil(this.headCount/2) * 330
        let scrollH = this.scroll.getComponent(UITransform).height
        if (allH > scrollH) {
            scrollH = allH
            this.scroll.content.getComponent(UITransform).height = scrollH
        }
        this.scroll.getComponent(ScrollView).scrollToTop()

        let disX = 350
        let disY = 330
        for (let index = 0; index < 4; index++) {
            let item = instantiate(this.headPrefab)
            item.parent = this.scroll.content

            let px = -175 + index%2*disX
            let py = scrollH - disY/2 - Math.floor(index/2)*disY
            item.setPosition(px,py)

            item.getComponent(HeadItem).setData(this, index)
            if (PD.user.headId == index){
                item.getComponent(HeadItem).setSelect(true)
                this.curItem = item.getComponent(HeadItem)
            }
            else{
                item.getComponent(HeadItem).setSelect(false)
            }
        }

        
    }

    // 选择头像
    selectHead(item) {
        this.curItem.setSelect(false)
        item.setSelect(true)
        this.curItem = item
    }

    /**
     * 确定更换
     */
    clickSure() {
        App.Audio.playOneShot("click")
        if (this.curItem.headId == PD.user.headId) {
            this.node.destroy()
            return
        }

        wsTool.send({msgCode:CommConst.Req_MODIFY_NICK, "nickname":null, "headId":this.curItem.headId})
        .then((data) => {
            if(data.result == 0) {
                showTip(App.language.getLanguageLab(185))
                PD.user.headId = this.curItem.headId
                App.Event.emit(EventConst.UPDATE_SET_HEAD)
                
                this.node.destroy()

            } else {
                showErrorTip(data.result)
            }
        })
    }

    /**
     * 取消
     */
    clickCancel() {
        App.Audio.playOneShot("click")
        this.node.destroy()
    }

}

